import { useSelector, useDispatch } from "react-redux"
import { useCallback } from "react";
import AddressApi from "../api/address.js"
import Creater from "../store/actions"
import { message } from "antd";

export const useAddress = () => {
  // 获取dispatch方法，需要使用其触发reducers 
  const dispatch = useDispatch();
  //获取状态机内address的状态值
  const address = useSelector(state => state.address)
  //从address对象内结构出当前页和每页显示条数
  const { curPage, eachPage } = address

  // 远程请求 获取自提点的数据
  const getAddress = useCallback(async () => {
    const data = await AddressApi.get({ curPage, eachPage })
    // 使用dispatch 触发reducer 将请求到的数据传进去作为参数传进去,覆盖掉初始状态值
    dispatch(Creater.getAddress(data))
  }, [curPage, eachPage, dispatch])

  // 修改当前页
  const setCurPage = useCallback((curPage) => {
    dispatch(Creater.addressSetCurPage({ curPage }))
  }, [dispatch]);

  // 修改每页显示条数
  const setEachPage = useCallback((eachPage) => {
    dispatch(Creater.addressSetEachPage({ eachPage }));
  }, [dispatch]);


  //新增自提点 
  const addAddress = useCallback(async (name, Adderss, longitude, latitude, Cold_store, Phone, Open_hours) => {
    const newDate = await AddressApi.addAddress(name, Adderss, longitude, latitude, Cold_store, Phone, Open_hours);
    return newDate
  });

  // 删除自提点
  const delAddress = useCallback(async (_id) => {
    const data = await AddressApi.deleteAddress(_id);
    return data;
  }, []);

  // 搜索 
  const onSearch = useCallback(async value => {
    const data = {
    }
    data.rows = await AddressApi.onSearch(value)
 
    dispatch(Creater.getAddress(data))

    return data.rows
  }, [dispatch])

  return [address, { getAddress, addAddress, delAddress, setCurPage, setEachPage, onSearch }]
}